# from typing import Optional
# from uuid import UUID
#
# from fastapi import Depends, Request, HTTPException
# from fastapi.security import OAuth2PasswordRequestForm
# from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin,exceptions
# from fastapi_users.db import BaseUserDatabase
#
# from core.mgr import get_user_db
# from db.models.users import User, UserDocument, UserCreate
# from core.config import settings
# from utils.result import Result
#
#
# class UserManager(UUIDIDMixin, BaseUserManager[User, str]):
#     reset_password_token_secret = settings.SECRET_KEY
#     verification_token_secret = settings.SECRET_KEY
#
#     async def create(self, user_create: UserCreate, safe: bool = False, request=None) -> Result:
#         # 检查 username 唯一性
#         await self.validate_username(user_create.username, request)
#         # 生成安全密码（如果需要）
#         if safe:
#             # 安全模式：排除敏感字段
#             user_dict = user_create.model_dump(exclude={"password"})
#             password = user_create.password  # 单独获取密码
#             user_dict["hashed_password"] = self.password_helper.hash(password)
#         else:
#             # 普通模式：包含所有字段
#             user_dict = user_create.model_dump()
#             password = user_dict.pop("password")
#             user_dict["hashed_password"] = self.password_helper.hash(password)
#
#         # 创建用户（跳过默认的邮箱唯一性检查）
#         created_user = await self.user_db.create(user_dict)
#
#         # 触发创建后钩子
#         await self.on_after_register(created_user, request)
#
#         return Result.success(data=created_user)
#
#     async def authenticate(self, credentials: OAuth2PasswordRequestForm) -> Result:
#         # 通过 username 查询用户（之前已实现）
#         user = await self.user_db.get_by_username(credentials.username)
#         if not user:
#             # 用户名不存在时，用无效密码执行一次验证（防时序攻击）
#             # self.password_helper.verify_and_update(credentials.password, "invalid_hash")
#             return Result.fail(msg="用户不存在")
#
#         # 验证密码（使用新方法 verify_and_update）
#         is_valid, _ = self.password_helper.verify_and_update(
#             credentials.password,
#             user.hashed_password
#         )
#         if not is_valid:  # 验证失败
#             return Result.fail(msg="用户名密码错误")
#
#         # 检查用户是否活跃
#         if not user.is_active:
#             return Result.fail(msg="用户未激活")
#
#         return Result.success(data= user)
#
#     # async def get_by_email(self, email: str) -> User:
#     #     user = await self.user_db.get_by_email(email)
#     #     if not user:
#     #         raise UserNotExists()
#     #     return user
#
#     async def on_after_register(self, user: User, request: Optional[Request] = None):
#         print(f"User {user.id} has registered.")
#
#     async def on_after_forgot_password(
#         self, user: User, token: str, request: Optional[Request] = None
#     ):
#         print(f"User {user.id} has forgot their password. Reset token: {token}")
#
#     async def on_after_request_verify(
#         self, user: User, token: str, request: Optional[Request] = None
#     ):
#         print(f"Verification requested for user {user.id}. Verification token: {token}")
#
#     async def validate_username(self, username: str, request: Optional[Request] = None) -> None:
#         if await self.user_db.get_by_username(username) is not None:
#             raise exceptions.UserAlreadyExists()
#
# # async def get_user_manager(user_db: BaseUserDatabase[User, UUID] = Depends(get_user_db)):
# #     yield UserManager(user_db)
#
# async def get_user_manager(user_db=Depends(get_user_db)):
#         yield UserManager(user_db)
#
